﻿#include "dbmanager.h"
#include <QUuid>
#include "jsontool.h"
#include <QSqlError>
dbManager::dbManager()
{
    //QSqlDatabase::addDatabase("QSQLITE");

}

bool dbManager::openDB(const QString& fileName,QString& uuid,QString& msg)
{
    // 动态生成一个唯一的连接名称
    QString dbConnectName = "Connection%1";
    dbConnectName = dbConnectName.arg(dbMap.size());
//    qInfo()<<"dbConnectName:"<< dbConnectName;
    // 创建数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE",dbConnectName);
    db.setDatabaseName(fileName);

    if (db.open()) {
        uuid = generaterUUID();
        dbMap.insert(uuid,db);
        return true;
    }
    msg = QStringLiteral("数据库打开失败！");
    return false;
}

bool dbManager::selectDataMultiple(const QString& sql,const QString& uuid,QString& msg,
                                 QJsonArray& jsonArray)
{
    if(dbMap.contains(uuid))
    {
        QSqlDatabase db = dbMap.find(uuid).value();
        if(db.isOpen())
        {
            try {
                // 执行数据库查询
                QSqlQuery query(db);
                if(query.exec(sql))
                {
                    QSqlRecord record = query.record();

                    // 遍历查询结果，动态地将每一行转换为 JSON 对象
                    while (query.next()) {
                        QJsonObject jsonObject;
                        // 动态获取字段数量和名称
                        int fieldCount = record.count();
                        for (int i = 0; i < fieldCount; ++i) {
                            QSqlField field = record.field(i);
                            QVariant value = query.value(i);
                            // 将字段名称和值添加到 JSON 对象
                            jsonObject[field.name()] = value.toString();
                        }
                        jsonArray.append(jsonObject);
                    }
                    return true;
                }else{
                    // 处理数据库查询失败的情况
                    msg = QStringLiteral("Database query failed: ") + query.lastError().text();
                }

            } catch (const std::exception& e) {
                // 捕获 C++ 异常
                msg = QStringLiteral("Caught exception: ") + e.what();
            } catch (...) {
                // 捕获其他异常
                msg = QStringLiteral("Caught an unknown exception.");
            }
        }
    }
    return false;
}

bool dbManager::selectDataSingle(const QString &sql, const QString &uuid, QString &msg,QJsonObject& jsonObject)
{
    if(dbMap.contains(uuid))
    {
        QSqlDatabase db = dbMap.find(uuid).value();
        if(db.isOpen())
        {
            try {
                // 执行数据库查询
                QSqlQuery query(db);
                if(query.exec(sql))
                {
                    QSqlRecord record = query.record();

                    // 遍历查询结果，动态地将每一行转换为 JSON 对象
                    while (query.next()) {
                        // 动态获取字段数量和名称
                        int fieldCount = record.count();
                        for (int i = 0; i < fieldCount; ++i) {
                            QSqlField field = record.field(i);
                            QVariant value = query.value(i);
                            // 将字段名称和值添加到 JSON 对象
                            jsonObject[field.name()] = value.toString();
                        }
                        break;
                    }
                    return true;
                }else{
                    // 处理数据库查询失败的情况
                    msg = QStringLiteral("Database query failed: ") + query.lastError().text();
                }

            } catch (const std::exception& e) {
                // 捕获 C++ 异常
                msg = QStringLiteral("Caught exception: ") + e.what();
            } catch (...) {
                // 捕获其他异常
                msg = QStringLiteral("Caught an unknown exception.");
            }
        }
    }
    return false;
}

bool dbManager::addData(const QString &sql, const QString uuid, QString &msg)
{
    if (dbMap.contains(uuid)) {
        QSqlDatabase db = dbMap.find(uuid).value();
        if(db.isOpen()){
            try {
                QSqlQuery query(db);
                if (query.exec(sql)) {
                    // 插入操作成功
                    msg = QStringLiteral("Database add success");
                    return true;
                } else {
                    // 处理数据库插入失败的情况
                    msg = QStringLiteral("Database insert failed: ") + query.lastError().text();
                }
            } catch (const std::exception& e) {
                // 捕获 C++ 异常
                msg = QStringLiteral("Caught exception: ") + e.what();
            } catch (...) {
                // 捕获其他异常
                msg = QStringLiteral("Caught an unknown exception.");
            }
        }
    }

    return false;
}

bool dbManager::deleteData(const QString &sql, const QString uuid, QString &msg)
{
    if (dbMap.contains(uuid)) {
        QSqlDatabase db = dbMap.find(uuid).value();
        if(db.isOpen()){
            try {
                QSqlQuery query(db);
                if (query.exec(sql)) {
                    // 删除操作成功
                    msg = QStringLiteral("Database delete success");
                    return true;
                } else {
                    // 处理数据库删除失败的情况
                    msg = QStringLiteral("Database delete failed: ") + query.lastError().text();
                }
            } catch (const std::exception& e) {
                // 捕获 C++ 异常
                msg = QStringLiteral("Caught exception: ") + e.what();
            } catch (...) {
                // 捕获其他异常
                msg = QStringLiteral("Caught an unknown exception.");
            }
        }
    }

    return false;
}

bool dbManager::updateData(const QString &sql, const QString uuid, QString &msg)
{
    if (dbMap.contains(uuid)) {
        QSqlDatabase db = dbMap.find(uuid).value();
        if(db.isOpen()){
            try {
                QSqlQuery query(db);
                if (query.exec(sql)) {
                    // 更新操作成功
                    msg = QStringLiteral("Database update success");
                    return true;
                } else {
                    // 处理数据库更新失败的情况
                    msg = QStringLiteral("Database update failed: ") + query.lastError().text();
                }
            } catch (const std::exception& e) {
                // 捕获 C++ 异常
                msg = QStringLiteral("Caught exception: ") + e.what();
            } catch (...) {
                // 捕获其他异常
                msg = QStringLiteral("Caught an unknown exception.");
            }
        }
    }

    return false;
}

QString dbManager::generaterUUID()
{
    // 生成一个新的 UUID
    QUuid uuid = QUuid::createUuid();

    // 将 UUID 转换为字符串
    QString uuidString = uuid.toString();
    return uuidString;
}
